package cn.iocoder.yudao.module.system.videostore;

import cn.iocoder.yudao.module.system.util.HttpUtils;
import cn.iocoder.yudao.module.system.videostore.dto.product.AddProductDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 视频号小店
 */
@Component
public class VideoStoreUtil {

    /**
     * 视频号小店 Appid
     */
    @Value("${wx.video-store.app-id}")
    private String videoStoreAppId;
    /**
     * 视频号小店 AppSecret
     */
    @Value("${wx.video-store.secret}")
    private String videoStoreSecret;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static String TOKEN_KEY = "video_store_token";

    //调用凭据
    private static final String stable_token = "https://api.weixin.qq.com/cgi-bin/token";
    //上传图片
    private static final String uploadImg = "https://api.weixin.qq.com/channels/ec/basics/img/upload";

    /**
     * 商品类目
     */
    //获取类目信息 根据三级类目ID获取类目的相关信息
    private static final String categoryDetail = "https://api.weixin.qq.com/channels/ec/category/detail";
    /**
     * 商品相关
     */
    //添加商品
    private static final String addProduct = "https://api.weixin.qq.com/channels/ec/product/add";

    /**
     * 获取 Access token  视频号小店 accessToken
     *
     * @return
     */
    public String getVideoStoreAccessToken() {
        String accessToken = null;
        boolean hasKey = stringRedisTemplate.hasKey(TOKEN_KEY);
        if (hasKey) {
            accessToken = stringRedisTemplate.opsForValue().get(TOKEN_KEY);
            System.err.println("=====================================accessToken");
            System.err.println(accessToken);
        } else {
            JSONObject requestBody = new JSONObject();
            Map<String, String> params = new HashMap<String, String>();
            params.put("appid", videoStoreAppId);
            params.put("secret", videoStoreSecret);
            params.put("grant_type", "client_credential");
            String res = null;
            try {
                res = HttpUtils.get(stable_token, params, requestBody.toJSONString());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (StringUtils.isNotBlank(res)) {
                    JSONObject result = JSONObject.parseObject(res);
                    if (result.containsKey("access_token")) {
                        accessToken = result.getString("access_token");
                        Integer expires_in = result.getInteger("expires_in");
                        //两小时过期
                        stringRedisTemplate.opsForValue().set(TOKEN_KEY, accessToken, Duration.ofSeconds(expires_in));
                    } else {
                        Integer errcode = result.getInteger("errcode");
                        String errmsg = result.getString("errmsg");
                        System.err.println("videoStoreGetAccessToken-errcode:" + errcode + ",videoStoreGetAccessToken-errmsg:" + errmsg);
                    }
                }
            }
        }
        return accessToken;
    }

    /**
     * 上传图片
     *
     * @param httpURL 图片路径
     * @return 图片路径
     */
    public String uploadVideoStoreImg(String httpURL) {
        String url = null;
        Map<String, String> params = new HashMap<String, String>();
        JSONObject requestBody = new JSONObject();
        requestBody.put("img_url", httpURL);
        String res = null;
        try {
            res = HttpUtils.post(uploadImg + "?access_token=" + getVideoStoreAccessToken() + "&upload_type=1&resp_type=1", params, requestBody.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (StringUtils.isNotBlank(res)) {
                JSONObject result = JSONObject.parseObject(res);
                Integer errcode = result.getInteger("errcode");
                if (errcode == 0) {
                    JSONObject picFile = result.getJSONObject("pic_file");
                    url = picFile.getString("img_url");
                } else {
                    String errmsg = result.getString("errmsg");
                    System.err.println("uploadVideoStoreImg-errcode:" + errcode + ",uploadVideoStoreImg-errmsg:" + errmsg);
                }
            }
        }
        return url;
    }

    /**
     * 根据三级类目ID获取类目的相关信息
     *
     * @param cat_id 三级类目ID
     * @return JSONObject
     */
    public JSONObject videoStoreCategoryDetail(String cat_id) {
        Map<String, String> params = new HashMap<String, String>();
        JSONObject requestBody = new JSONObject();
        requestBody.put("cat_id", cat_id);
        String res = null;
        JSONObject result = null;
        try {
            res = HttpUtils.post(categoryDetail + "?access_token=" + getVideoStoreAccessToken(), params, requestBody.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (StringUtils.isNotBlank(res)) {
                result = JSONObject.parseObject(res);
                Integer errcode = result.getInteger("errcode");
                if (errcode == 0) {
                    //info
                    //attr
                } else {
                    String errmsg = result.getString("errmsg");
                    System.err.println("getGiftCard-errcode:" + errcode + ",getGiftCard-errmsg:" + errmsg);
                }
            }
        }
        return result;
    }

    /**
     * 添加商品
     *
     * @param addProductDTO addProductDTO
     * @return String
     */
    public String addVideoStoreProduct(AddProductDTO addProductDTO) {
        String requestBody = JSON.toJSONString(addProductDTO);
        System.out.println("addVideoStoreProduct:" + requestBody);
        Map<String, String> params = new HashMap<String, String>();
        String res = null;
        String product_id = null;
        try {
            res = HttpUtils.post(addProduct + "?access_token=" + getVideoStoreAccessToken(), params, requestBody);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (StringUtils.isNotBlank(res)) {
                JSONObject result = JSONObject.parseObject(res);
                Integer errcode = result.getInteger("errcode");
                if (errcode == 0) {
                    JSONObject data = result.getJSONObject("data");
                    product_id = data.getString("product_id");
                } else {
                    String errmsg = result.getString("errmsg");
                    System.err.println("addVideoStoreProduct-errcode:" + errcode + ",addVideoStoreProduct-errmsg:" + errmsg);
                }
            }
        }
        return product_id;
    }

}
